#include "logindialog.h"
#include "ui_logindialog.h"
#include <QMessageBox>
#include <QSqlQuery>
#include <QSettings>
#include <registerdialog.h>
#include "Chatroom.h"
QString getname;
Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Dialog)
{
    ui->setupUi(this);
    QPixmap pix1 (":/myimages/4.jpg");
    ui->label->setPixmap(pix1);
    QPixmap pix2 (":/myimages/2.jpg");
    ui->label_3->setPixmap(pix2);
    ui->passwordlineEdit->setEchoMode(QLineEdit::Password);
    QSettings settings("Myapp", "Login");
    QString username = settings.value("username").toString();
    QString password = settings.value("password").toString();
    ui->usernamelineEdit->setText(username);
    if (!password.isEmpty()) {
        ui->passwordlineEdit->setText(password);
        ui->remembercheckBox->setChecked(true);
    }
    getname=username;

}

Dialog::~Dialog()
{
    delete ui;
}


void Dialog::on_loginButton_clicked()
{

    QString username = ui->usernamelineEdit->text();
    QString password = ui->passwordlineEdit->text();
    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "警告", "账号或密码不能为空！");
        return;
    }

    // 查询账号
    QSqlQuery query;
    query.prepare("SELECT * FROM users WHERE username = :username AND password = :password");
    query.bindValue(":username", username);
    query.bindValue(":password", password);
    if (!query.exec()) {
        QMessageBox::warning(this, "警告", "查询失败：" + query.lastError().text());
        return;
    }
    if (!query.next()) {
        QMessageBox::warning(this, "警告", "用户名或密码错误");
        ui->passwordlineEdit->clear();
        return;
    }

    // 登录成功，进行后续操作

    if(ui->remembercheckBox->isChecked()){
        QSettings settings("Myapp","Login");
        settings.setValue("username",username);
        settings.setValue("password",password);
    }else{
         QSettings settings("Myapp","Login");
        settings.setValue("username",username);
        settings.remove("password");
    }
    Chatroom *b = new Chatroom(username);
    b->show();
    this->hide();

}


void Dialog::on_registerButton_clicked()
{
     registerDialog *c = new registerDialog();
    c->show();
    this->hide();

}

void Dialog::on_remembercheckBox_clicked()
{
    if(ui->remembercheckBox->isChecked())
    {
        remebercheck = true;
    }
    else
    {
        ui->passwordlineEdit->clear();
       remebercheck = false;
    }

}

